<template>
  <div>
    <MyTable :arr="list">
      <!-- v-slot: ===# -->
      <template #title
        ><th>#</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>标签</th>
        <th>操作</th>
      </template>
      <template #tbody="scope"
        ><td>{{ scope.row.id }}</td>
        <td>{{ scope.row.goods_name }}</td>
        <td>{{ scope.row.goods_price }}</td>
        <td>
          <input
            type="text"
            class="tag-input form-control"
            style="width: 100px"
            v-if="scope.row.inputVisible"
            v-focus
            @blur="scope.row.inputVisible = false"
            v-model="scope.row.inputValue"
            @keydown.esc="scope.row.inputValue = ''"
            @keydown.enter="addtagFn(scope)"
          />
          <button
            v-else
            style="display: block"
            class="btn btn-primary btn-sm add-tag"
            @click="scope.row.inputVisible = true"
          >
            +Tag
          </button>
          <span
            v-for="(str, index) in scope.row.tags"
            :key="index"
            class="badge badge-warning"
            >{{ str }}</span
          >
        </td>
        <td>
          <button class="btn btn-danger btn-sm" @click="delFn(scope.row.id)">
            删除
          </button>
        </td></template
      >
    </MyTable>
  </div>
</template>

<script>
import MyTable from '../components/MyTable.vue'
export default {
  components: {
    MyTable,
  },
  data() {
    return {
      list: [], // 所有数据
    }
  }, //请求数据在生命周期created--得到数据赋值给list
  created() {
    this.$axios({
      url: '/api/goods',
      methods: 'get',
    }).then((res) => {
      this.list = res.data.data
    })
  },
  methods: {
    delFn(id) {
      //删除功能
      this.list = this.list.filter((item) => item.id !== id)
    },
    //当我点击回车触发这个事件把输入框的值添加到tags中--并且把每一行数据传递到添加事件中可以操作数据进行添加
    addtagFn(scope) {
      if (scope.row.inputValue.trim() === '') return alert('请输入数据')
      scope.row.tags.push(scope.row.inputValue)
      scope.row.inputValue = ''
    },
  },
  //自定义指令-输入框自动聚焦//el第一个参数是需要操作的dom元素
  directives: {
    focus: {
      inserted(el) {
        el.focus()
      },
    },
  },
}
</script>
<style scoped>
.badge {
  background-color: #fdc828;
  color: black;
}
span {
  margin: 2px;
}
</style>
